﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.ComponentModel;
using System.Windows;
using System.Reflection;
using System.Collections.Concurrent;

namespace ShredTheLog.Controls
{
    public sealed class AutoScrollViewer : ScrollViewer
    {
        private static void ScrollableHeightChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var sender = (AutoScrollViewer)d;
            if (Math.Abs((double)e.OldValue - sender.VerticalOffset) < 1)
                sender.ScrollToBottom();
        }

        static AutoScrollViewer()
        {
            var scrollableHeightPropertyKey = (DependencyPropertyKey)typeof(ScrollViewer).GetField("ScrollableHeightPropertyKey", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);
            ScrollViewer.ScrollableHeightProperty.OverrideMetadata(typeof(AutoScrollViewer), new FrameworkPropertyMetadata(0.0, ScrollableHeightChanged), scrollableHeightPropertyKey);
        }

        public AutoScrollViewer()
        {
            this.ScrollToBottom();
        }
    }
}
